package org.hilo.boot.core.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionManager;

/**
 * Compatible get session id from header
 * 
 * @author zollty
 * @since 2018-09-02
 */
public class HeaderBasedWebSessionManager extends DefaultWebSessionManager implements WebSessionManager {
    
    public static final String HEADER_SESSION_ID_NAME = "X-TOKEN";
    
    private String headerTokenName;
    
    public HeaderBasedWebSessionManager() {
        super();
        this.headerTokenName = HEADER_SESSION_ID_NAME;
    }

    public HeaderBasedWebSessionManager(String headerTokenName) {
        super();
        this.headerTokenName = headerTokenName;
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        Serializable id = super.getSessionId(request, response);
        if (id != null) {
            return id;
        }
        id = getSessionIdFromHeader((HttpServletRequest) request);
        if (id != null) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            // automatically mark it valid here. If it is invalid, the
            // onUnknownSession method below will be invoked and we'll remove the attribute at that time.
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
        }
        return id;
    }

    private Serializable getSessionIdFromHeader(HttpServletRequest request) {
        return request.getHeader(headerTokenName); // JSESSIONID
    }

    /**
     * @return the headerTokenName
     */
    public String getHeaderTokenName() {
        return headerTokenName;
    }

    /**
     * @param headerTokenName the headerTokenName to set
     */
    public void setHeaderTokenName(String headerTokenName) {
        this.headerTokenName = headerTokenName;
    }
    
    // since 1.2.1
//    private String getSessionIdName() {
//        String name = getSessionIdCookie() != null ? getSessionIdCookie().getName() : null;
//        if (name == null) {
//            name = ShiroHttpSession.DEFAULT_SESSION_ID_NAME;
//        }
//        return name;
//    }

}
